"""
主题: 定义上下文管理器的简单方法
问题: 你想自己去实现一个新的上下文管理器，以便使用with语句。
提示 : 
"""

import time
from contextlib import contextmanager

import time

class timethis:
    def __init__(self, label):
        self.label = label

    def __enter__(self):
        self.start = time.time()

    def __exit__(self, exc_ty, exc_val, exc_tb):
        end = time.time()
        print('{}: {}'.format(self.label, end - self.start))

@contextmanager
def timethis_wrap(label):
    start = time.time()
    try:
        yield
    finally:
        end = time.time()
        print('{}: {}'.format(label, end - start))

@contextmanager
def list_transaction(orig_list):
    '''列表对象上的某种事务'''
    working = list(orig_list)
    yield working
    orig_list[:] = working


def recipe1():
    with timethis('timethis'):
        n = 10000000
        while n > 0:
            n -= 1 

    with timethis_wrap('timethis_wrap'):
        n = 10000000
        while n > 0:
            n -= 1 

def recipe2():
    items = [1, 2, 3]
    with list_transaction(items) as working:
        working.append(4)
        working.append(5)
    print(f"{items = }")

    try:
        with list_transaction(items) as working:
            working.append(6)
            working.append(7)
            raise RuntimeError('oops')
    except RuntimeError as e:
        print(e)  
    finally: 
        print(f"{items = }")

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()

if __name__ == '__main__':
    main()                        